import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

// vuex 部分数据持久化
const handleStore = (store) => {
    if (localStorage._appName)
        store.commit('setAppName', localStorage._appName);
    if (localStorage._user)
        store.commit('setUser', localStorage._user);
    if (localStorage._token)
        store.commit('setToken', localStorage._token);
    if (localStorage._role !== undefined)
        store.commit('setRole', parseInt(localStorage._role));

    store.subscribe((mutation, state) => {
        if (state.appName)
            localStorage.setItem('_appName', state.appName);
        else
            localStorage.removeItem('_appName');
        if (state.user)
            localStorage.setItem('_user', state.user);
        else
            localStorage.removeItem('_user');
        if (state.token)
            localStorage.setItem('_token', state.token);
        else
            localStorage.removeItem('_token');
        if (state.role === -1)
            localStorage.removeItem('_role');
        else
            localStorage.setItem('_role', state.role);
    });
};

export default new Vuex.Store({
    state: {
        init: false,
        appName: null,
        token: null,
        user: null,
        role: -1,
        isLoggedIn: false,
        isAdmin: false,
    },
    mutations: {
        init(state, info) {
            state.appName = info.appName;
            state.init = true;
        },
        setAppName(state, appName) {
            state.appName = appName;
        },
        setToken(state, token) {
            state.token = token;
            state.isLoggedIn = !!token;
        },
        setUser(state, user) {
            state.user = user;
        },
        setRole(state, role) {
            state.role = role;
            state.isAdmin = role === 0;
        },
    },
    actions: {
        setToken({commit}, token) {
            commit('setToken', token);
        },
        setUser({commit}, user) {
            commit('setUser', user);
        },
        setRole({commit}, role) {
            commit('setRole', role);
        },
        logout({commit}) {
            commit('setToken', null);
            commit('setUser', null);
            commit('setRole', -1);
        },
    },
    plugins: [handleStore],
});
